package com.yuncheng.spcyApi.controller;

import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.spcyApi.entity.SpcyRsJcxm;
import com.yuncheng.spcyApi.service.ISpcyRsJcxmService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import utils.LogUtils;
import utils.ObjectToMapUtils;

/**
 * @Description: 审评查验-检查项目库
 * @Author: csx
 * @Date: 2023-03-03
 * @Version: V1.0
 */
@Api(tags = "审评查验-检查项目库接口")
@RestController
@RequestMapping("/api/spzx-spcy/spcyRsJcxm")
public class SpcyRsJcxmController extends BaseController<SpcyRsJcxm, ISpcyRsJcxmService> {

    private static final Logger log = LoggerFactory.getLogger(SpcyRsJcxmController.class);

    @Resource
    private ISpcyRsJcxmService spcyRsJcxmService;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private MyExcelUtils myExcelUtils;

    @Resource
    private ISpcyLogService spcyLogService;

    /**
     * 分页列表查询
     *
     * @param spcyRsJcxm
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Log(title = "审评查验-检查项目库-分页列表查询")
    @ApiOperation(value = "审评查验-检查项目库-分页列表查询")
    @GetMapping(value = "/list")
    public HttpResult<?> queryPageList(SpcyRsJcxm spcyRsJcxm, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SpcyRsJcxm> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<SpcyRsJcxm> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(spcyRsJcxm.getFywflcode()),SpcyRsJcxm::getFywflcode,spcyRsJcxm.getFywflcode());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsJcxm.getFtype1()),SpcyRsJcxm::getFtype1,spcyRsJcxm.getFtype1());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsJcxm.getFtype2()),SpcyRsJcxm::getFtype2,spcyRsJcxm.getFtype2());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsJcxm.getFtype3()),SpcyRsJcxm::getFtype3,spcyRsJcxm.getFtype3());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsJcxm.getFtype4()),SpcyRsJcxm::getFtype4,spcyRsJcxm.getFtype4());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsJcxm.getFtype5()),SpcyRsJcxm::getFtype5,spcyRsJcxm.getFtype5());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsJcxm.getFtype6()),SpcyRsJcxm::getFtype6,spcyRsJcxm.getFtype6());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsJcxm.getFtype7()),SpcyRsJcxm::getFtype7,spcyRsJcxm.getFtype7());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsJcxm.getFtype8()),SpcyRsJcxm::getFtype8,spcyRsJcxm.getFtype8());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsJcxm.getFcontent1()),SpcyRsJcxm::getFcontent1,spcyRsJcxm.getFcontent1());
        queryWrapper.like(StringUtils.isNotEmpty(spcyRsJcxm.getFcontent2()),SpcyRsJcxm::getFcontent2,spcyRsJcxm.getFcontent2());
        queryWrapper.orderByAsc(SpcyRsJcxm::getFtype2);
        queryWrapper.orderByAsc(SpcyRsJcxm::getFxh);
        queryWrapper.orderByAsc(SpcyRsJcxm::getCreateTime);
        IPage<SpcyRsJcxm> pageList = spcyRsJcxmService.page(page, queryWrapper);
        return HttpResult.ok(pageList);
    }



    /**
     * 添加
     *
     * @param spcyRsJcxm
     * @return
     */
    @Log(title = "审评查验-检查项目库-添加")
    @ApiOperation(value = "审评查验-检查项目库-添加")
    @PostMapping(value = "/add")
    public HttpResult<?> add(@RequestBody SpcyRsJcxm spcyRsJcxm) {
        spcyRsJcxm.setId(GetUuIdUtils.ReplaceUuId());
        if (StringUtils.isBlank(spcyRsJcxm.getFywflcode())){
            return HttpResult.error("业务分类不能为空");
        }
        spcyRsJcxm.setFtype1(SpcyConstant.getYwclNameByCode(spcyRsJcxm.getFywflcode()));
        spcyRsJcxmService.save(spcyRsJcxm);

        String operContent = "新增信息：";

        // 将map里面的属性和值转String
        Map<String, Object> beanMap = ObjectToMapUtils.objectToMap(spcyRsJcxm);
        operContent += LogUtils.MapToStringMethod(beanMap);
        spcyLogService.addLogs(LogConstant.LOGS_RS_JCXM,operContent,spcyRsJcxm.getId(), LogConstant.LOGS_RS_JCXM, SpcyConstant.LOGS_SYS_TYPE_XZ);
        return HttpResult.ok("添加成功");
    }

    /**
     * 编辑

     * @return
     */
    @Log(title = "审评查验-检查项目库-编辑")
    @ApiOperation(value = "审评查验-检查项目库-编辑")
    @ApiImplicitParam(name = "id",value = "检查项目库id",required = true)
    @PutMapping(value = "/edit")
    public HttpResult<?> edit(@RequestBody HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException{
        if (StringUtils.isEmpty(buffer.get("id"))){
            return HttpResult.error("检查项目库信息id不能为空");
        }
        String qyId = buffer.get("id");
        SpcyRsJcxm oldJcxm = spcyRsJcxmService.getById(qyId);
        SpcyRsJcxm oldJcxmUpdate = spcyRsJcxmService.getById(qyId);
        if (oldJcxmUpdate == null){
            return HttpResult.error("当前检查项目库信息数据不存在，请重试");
        }
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(oldJcxmUpdate, buffer);
        spcyRsJcxmService.updateById(oldJcxmUpdate);

        String operContent = "基本信息修改：";
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldJcxm);
        operContent += LogUtils.BeanModifyMsg(oldJcxmUpdate,oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_RS_JCXM,operContent,qyId,LogConstant.LOGS_RS_JCXM,SpcyConstant.LOGS_SYS_TYPE_XG);
        return HttpResult.ok("修改成功");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @Log(title = "审评查验-检查项目库-通过id删除")
    @ApiOperation(value = "审评查验-检查项目库-通过id删除")
    @DeleteMapping(value = "/delete")
    public HttpResult<?> delete(@RequestParam("id") String id) {
        if (StringUtils.isEmpty(id)){
            return HttpResult.error("id参数不能为空");
        }
        SpcyRsJcxm nowQy = spcyRsJcxmService.getById(id);
        if (nowQy == null){
            return HttpResult.error("当前检查项目库信息数据不存在，请重试");
        }
        spcyRsJcxmService.removeById(id);
        String operContent = "删除信息：";
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(nowQy);
        operContent += LogUtils.MapToStringMethod(oldMap);
        spcyLogService.addLogs(LogConstant.LOGS_RS_JCXM,operContent,id,LogConstant.LOGS_RS_JCXM,SpcyConstant.LOGS_SYS_TYPE_SC);
        return HttpResult.ok("删除成功");
    }

    /**
     * 通过id批量删除
     *
     * @param ids
     * @return
     */
    @Log(title = "审评查验-检查项目库-批量删除")
    @ApiOperation(value = "审评查验-检查项目库-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public HttpResult<?> deleteBatch(@RequestParam("ids") String ids) {
        if (StringUtils.isEmpty(ids)){
            return HttpResult.error("ids参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));
        List<SpcyRsJcxm> spcyQyJbxxes = spcyRsJcxmService.listByIds(idsList);
        if (CollectionUtils.isEmpty(spcyQyJbxxes)){
            return HttpResult.error("数据不存在，请重试");
        }
        String operContent = "";
        for (SpcyRsJcxm qyJbxx : spcyQyJbxxes){
            String id = qyJbxx.getId();
            spcyRsJcxmService.removeById(id);

            operContent = "删除信息：";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(qyJbxx);
            operContent += LogUtils.MapToStringMethod(oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_RS_JCXM,operContent,id,LogConstant.LOGS_RS_JCXM,SpcyConstant.LOGS_SYS_TYPE_SC);
            operContent = "";
        }

        return HttpResult.ok("删除成功");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @Log(title = "审评查验-检查项目库-通过id查询")
    @ApiOperation(value = "审评查验-检查项目库-通过id查询")
    @GetMapping(value = "/queryById")
    public HttpResult<?> queryById(@RequestParam("id") String id) {
        SpcyRsJcxm spcyRsJcxm = spcyRsJcxmService.getById(id);
        return HttpResult.ok(spcyRsJcxm);
    }

    /**
     * 数据转换
     * @param spcyRsJcxm
     */
    private void formatValue(SpcyRsJcxm spcyRsJcxm){
    }

    @Log(title = "导入检查项目库数据-表格excel")
    @ApiOperation(value = "导入检查项目库数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file",value = "excel模板文件",required = true),
            @ApiImplicitParam(name = "fywflcode",value = "业务分类编码",required = true)
    })
    @PostMapping(value = "impRsJcxmData")
    public HttpResult<?> impRsJcxmData(@RequestParam("file") MultipartFile file,
                                       @RequestParam(value = "fywflcode",defaultValue = "")String ywflCode,
                                       @RequestParam(value = "code", defaultValue = "") String code){
        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx"))
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");

        File fileUpload = localFileUploadUtils.uploadDempFile(file,fileName);
        // 获取导入的数据
        List<Map<String, Object>> mapsList = null;
        try {
            mapsList = myExcelUtils.paresExclToMapList(BusinessConstant.getJcxmMbXml(ywflCode), fileUpload);
        } catch (Exception e) {
            log.error("导入检查项目库数据出错-{}",e.getMessage());
        }

        if (StringUtils.isNotBlank(code)){
            ywflCode = code;
        }

        if (CollectionUtils.isNotEmpty(mapsList) && mapsList.size() > 0) {
            for (Map map : mapsList) {
                spcyRsJcxmService.impRsJcxmData(map, ywflCode);
            }
        }
        fileUpload.delete();
        return HttpResult.ok("导入成功");
    }


    @Log(title = "下载检查项目-导入模板")
    @ApiOperation(value = "下载检查项目-导入模板")
    @GetMapping("/downRsJcxmTemplate")
    public void downRsJcxmTemplate(@RequestParam(value = "fywflcode",defaultValue = "")String fywflcode, HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("JcxmImpTemplate.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.getJcxmMbXml(fywflcode), out);
        } catch (Exception e) {
            log.error("下载检查项目库模板错误-{}",e.getMessage());
        }
    }

    @Log(title = "导出检查项目库数据-表格excel")
    @ApiOperation(value = "导出检查项目库数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "ids",value = "检查项目字符逗号分割",dataType = "String")
    })
    @GetMapping("/exportRsJcxmData")
    public void exportRsJcxmData(@RequestParam(value = "ids",defaultValue = "")String ids,
                                SpcyRsJcxm spcyRsJcxm,
                                HttpServletResponse response,HttpServletRequest request){
        try {
            String name = "exportRsJcxm";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<String> IdsList = Arrays.asList(ids.split(","));
            List<Object> list = new ArrayList<>(); // 导出的数据
            // 多选导出
            if (StringUtils.isNotEmpty(ids)) {
                List<SpcyRsJcxm> rsJcxmList = spcyRsJcxmService.listByIds(IdsList);
                if (CollectionUtils.isNotEmpty(rsJcxmList)){
                    for (SpcyRsJcxm e : rsJcxmList){
                        list.add(e);
                    }
                }
            }else {
                LambdaQueryWrapper<SpcyRsJcxm> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(StringUtils.isNotEmpty(spcyRsJcxm.getFywflcode()),SpcyRsJcxm::getFywflcode,spcyRsJcxm.getFywflcode());
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsJcxm.getFtype1()),SpcyRsJcxm::getFtype1,spcyRsJcxm.getFtype1());
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsJcxm.getFtype2()),SpcyRsJcxm::getFtype2,spcyRsJcxm.getFtype2());
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsJcxm.getFtype3()),SpcyRsJcxm::getFtype3,spcyRsJcxm.getFtype3());
                queryWrapper.like(StringUtils.isNotEmpty(spcyRsJcxm.getFtype4()),SpcyRsJcxm::getFtype4,spcyRsJcxm.getFtype4());
                queryWrapper.orderByAsc(SpcyRsJcxm::getFtype1);
                queryWrapper.orderByAsc(SpcyRsJcxm::getFxh);
                queryWrapper.orderByAsc(SpcyRsJcxm::getCreateTime);
                List<SpcyRsJcxm> rsJcxmList = spcyRsJcxmService.list(queryWrapper);
                if (CollectionUtils.isNotEmpty(rsJcxmList)){
                    for (SpcyRsJcxm e : rsJcxmList){
                        list.add(e);
                    }
                }
            }

            myExcelUtils.outputListToExclFile(BusinessConstant.getJcxmMbXml(spcyRsJcxm.getFywflcode()), list, out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出观察员数据出错-{}",e.getMessage());
        }
    }
}
